/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package yuhuibear.poat.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import yuhuibear.poat.object.mapEntity.DataBaseMapper;

/**
 * 
 * @author yuhuibear
 */
public class SequenceTool {

	private static Log log = LogFactory.getLog(DataBaseMapper.class);

	public static void fix(DataSource source) throws Exception {
		Connection con = source.getConnection();
		String sql = "select relname from pg_class where relkind='S' and relnamespace=(select oid from pg_namespace where nspname='public')";
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery(sql);
		List<String> seqs = new LinkedList<String>();
		while (rs.next()) {
			String seq = rs.getString(1);
			if (!seq.endsWith("_id_seq")) {
				continue;
			}
			seqs.add(seq);
		}
		int cnt = 0;
		for (String seq : seqs) {
			String table = seq.substring(0, seq.length() - "_id_seq".length());
			sql = "select setval('" + seq + "', (select max(id) from " + table
					+ "))";
			st.execute(sql);
			cnt++;
			log.debug("fix sequence of " + table + ": succeed.");
		}
		log.info(String.format("fixed %d sequences in total.", cnt));
	}

	public static void setSequenceTo(DataSource source, String table, long value)
			throws Exception {
		Connection con = source.getConnection();
		String sql = "select setval('" + table + "_id_seq', " + value + ")";
		Statement st = con.createStatement();
		st.execute(sql);
		log.debug("fix sequence of " + table + ": succeed.");
	}

	public static void fix(DataSource source, int value) throws Exception {
		Connection con = source.getConnection();
		String sql = "select relname from pg_class where relkind='S' and relnamespace=(select oid from pg_namespace where nspname='public')";
		Statement st = con.createStatement();
		ResultSet rs = st.executeQuery(sql);
		List<String> seqs = new LinkedList<String>();
		while (rs.next()) {
			String seq = rs.getString(1);
			if (!seq.endsWith("_id_seq")) {
				continue;
			}
			seqs.add(seq);
		}
		int cnt = 0;
		for (String seq : seqs) {
			String table = seq.substring(0, seq.length() - "_id_seq".length());
			sql = "select setval('" + seq + "', " + value + ")";
			st.execute(sql);
			cnt++;
			log.debug("fix sequence of " + table + ": succeed.");
		}
		log.info(String.format("fixed %d sequences in total.", cnt));
	}
}
